<!-- 登录日志 -->
<template>
  <div id="loginlogs">
    <!-- 搜索内容 -->
    <div
      class="search"
      :style="{
        backgroundColor: bgcColor.color === '#000' ? '#fff' : 'rgb(33, 33, 48)',
        color: bgcColor.color === '#000' ? '#000' : 'rgb(33, 33, 48)'
      }"
    >
      <el-row :gutter="20">
        <el-col :lg="8" :md="12">
          <div class="list">
            <div
              class="tit"
              :style="{
                color: bgcColor.color === '#000' ? '#393939' : '#fff'
              }"
            >
              用户名
            </div>
            <!-- <input
              type="text"
              placeholder="输入用户名查找"
              v-model="state.serchName"
              :style="{
                color: bgcColor.color === '#000' ? '#6e6e6e' : '#fff',
                backgroundColor:
                  bgcColor.color === '#000' ? '#fff' : 'rgb(46, 46, 64)',
                borderColor:
                  bgcColor.color === '#000'
                    ? 'rgb(245, 245, 245)'
                    : 'rgb(46, 46, 64)'
              }"
            /> -->
            <el-select
              v-model="state.serchName"
              class="m-2"
              placeholder="Select"
              size="large"
              :style="{
                color: bgcColor.color === '#000' ? '#6e6e6e' : '#fff',
                backgroundColor:
                  bgcColor.color === '#000' ? '#fff' : 'rgb(46, 46, 64)',
                borderColor:
                  bgcColor.color === '#000'
                    ? 'rgb(245, 245, 245)'
                    : 'rgb(46, 46, 64)'
              }"
            >
              <el-option
                v-for="item in state.amdintorList"
                :key="item._id"
                :label="item.name"
                :value="item._id"
              />
            </el-select>
          </div>
        </el-col>
        <el-col :lg="8" :md="12">
          <div class="list">
            <div
              class="tit"
              :style="{
                color: bgcColor.color === '#000' ? '#393939' : '#fff'
              }"
            >
              时间
            </div>
            <el-date-picker
              v-model="state.searchTime"
              type="datetimerange"
              :shortcuts="state.shortcuts"
              range-separator="To"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </div>
        </el-col>
        <el-col :lg="8" :md="12">
          <div class="list">
            <div
              class="tit"
              :style="{
                color: bgcColor.color === '#000' ? '#393939' : '#fff'
              }"
            >
              登录设备
            </div>
            <el-select
              v-model="state.serchEquipment"
              class="m-2"
              placeholder="Select"
              size="large"
            >
              <el-option
                v-for="item in state.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </el-col>
      </el-row>
      <el-row justify="end">
        <el-col :lg="3" :md="6">
          <div class="submit" @click="serchList">搜索</div>
        </el-col>
      </el-row>
    </div>
    <!-- 表单内容 -->
    <div
      class="center"
      :style="{
        backgroundColor: bgcColor.color === '#000' ? '#fff' : 'rgb(33, 33, 48)',
        color: bgcColor.color === '#000' ? '#000' : 'rgb(33, 33, 48)'
      }"
    >
      <el-table :data="state.journalList" stripe style="width: 100%">
        <el-table-column
          label="登录时间"
          align="center"
          width="180"
          v-format-time
        >
          <template #default="scope">
            <span>{{ dayjs(scope.row.time, true) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="author.name"
          label="用户名"
          align="center"
          width="180"
        />
        <el-table-column label="头像" align="center" width="180">
          <template #default="scope">
            <img :src="baseURL + scope.row.author?.avatar" />
          </template>
        </el-table-column>
        <el-table-column label="登录设备" align="center">
          <template #default="scope">
            <span v-conversion-equipment>{{ scope.row.equipment }}</span>
          </template>
        </el-table-column>
        <el-table-column label="IP地址" align="center">
          <template #default="scope">
            <span v-conversion-equipment>{{ scope.row.loginIP }}</span>
          </template>
        </el-table-column>
        <el-table-column label="位置信息" align="center">
          <template #default="scope">
            <span v-conversion-equipment>{{ scope.row.loginPosition }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button
              type="danger"
              :icon="Delete"
              circle
              @click="handleDelete(scope.row._id)"
          /></template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:currentPage="state.currentPage"
          v-model:page-size="state.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="state.allNums"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, computed } from 'vue'
import { useStore } from 'vuex'
import {
  journalListData,
  searchloginJournal,
  deleteJournal
} from '@/server/serve/api_journal'
import { getAdmintorList } from '@/server/serve/api_admintor'
import type { JournalListDataTypes } from '@/server/serve/api_journal'
import type { RequsetAdmintorListDataTypes } from '@/server/serve/api_admintor'
import { baseURL } from '@/utils/axios'
import dayjs from '@/utils/dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'

const store = useStore()

const bgcColor = computed(() => store.state.Background)

const state = reactive({
  // 日志列表
  journalList: [] as Array<JournalListDataTypes>,
  // 该分类日志总数量
  allNums: 10000,
  // 当前分页指向页数
  currentPage: 1,
  // 当前每页显示的条数
  pageSize: 10,
  // 搜索用户名
  serchName: '',
  // 搜索时间范围
  searchTime: '',
  // 登录设备
  serchEquipment: 3,
  // 管理员列表
  amdintorList: [] as Array<RequsetAdmintorListDataTypes>,
  // 设备类型
  options: [
    {
      value: 3,
      label: '全部'
    },
    {
      value: 0,
      label: 'PC端'
    },
    {
      value: 1,
      label: '手机端(Android)'
    },
    {
      value: 2,
      label: '手机端(iPhone)'
    }
  ],
  // 时间范围
  shortcuts: [
    {
      text: 'Last week',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
        return [start, end]
      }
    },
    {
      text: 'Last month',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
        return [start, end]
      }
    },
    {
      text: 'Last 3 months',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
        return [start, end]
      }
    }
  ],
  // 当前列表数据渲染模式, 是基于原始还是基于搜索,默认原始
  journalListTypeOrlist: true
})

// 渲染列表数据 基于不同情况不同渲染
const listRendering = (type = true) => {
  // 基于原始
  if (type) {
    // 分页索引指向1
    // state.currentPage = 1
    // 请求列表数据
    journalListData(
      0,
      state.pageSize,
      (state.currentPage - 1) * state.pageSize
    ).then(({ data }) => {
      state.journalList = data.data?.journalList as Array<JournalListDataTypes>
      state.allNums = data.data?.allNums as number
      console.log(state.journalList)
    })
  }
  // 基于搜索
  else {
    if (!state.serchName)
      return ElMessage({
        type: 'warning',
        message: '请选择用户昵称'
      })
    // 分页索引指向1
    // state.currentPage = 1

    const startTime = new Date(state.searchTime[0]).getTime()
    const endTime = new Date(state.searchTime[1]).getTime()
    searchloginJournal(
      state.serchName,
      startTime,
      endTime,
      state.serchEquipment,
      state.pageSize,
      (state.currentPage - 1) * state.pageSize
    ).then(({ data: serchResult }) => {
      // 赋值日志列表
      state.journalList = serchResult.data
        ?.journalList as Array<JournalListDataTypes>
      // 赋值日志总数量
      state.allNums = serchResult.data?.allNums as number
    })
  }
}

// 切换每页展示条数
const handleSizeChange = async (val: number) => {
  state.pageSize = val
  listRendering(state.journalListTypeOrlist)
}
// 切换不同页码
const handleCurrentChange = async (val: number) => {
  state.currentPage = val
  listRendering(state.journalListTypeOrlist)
}

// 初始化 请求数据
listRendering()

// 获取管理员列表
getAdmintorList().then(({ data }) => {
  state.amdintorList = data.data
    ?.admintorList as Array<RequsetAdmintorListDataTypes>
})

// 搜索内容
const serchList = () => {
  state.journalListTypeOrlist = false
  listRendering(state.journalListTypeOrlist)
}

// 删除日志
const handleDelete = (journalID: string) => {
  ElMessageBox.confirm('确认删除该日志信息吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const { data: journalData } = await deleteJournal(journalID)
      if (journalData.code)
        return ElMessage({
          type: 'warning',
          message: journalData.mes
        })
      ElMessage({
        type: 'success',
        message: journalData.mes
      })
      const findIndex = state.journalList.findIndex(
        (item) => item._id === journalID
      )
      state.journalList.splice(findIndex, 1)
    })
    .catch(() => {
      console.log()
    })
}
</script>

<style scoped lang="less">
#loginlogs {
  .search {
    border-radius: 16px;
    padding: 0 15px 10px;
    .list {
      margin-top: 15px;
      display: flex;
      align-items: center;
      .tit {
        color: #393939;
        font-size: 13px;
        width: 70px;
      }
      input {
        border-radius: 16px;
        outline: none;
        height: 42px;
        text-indent: 1em;
        display: block;
        width: 100%;
        color: #6e6e6e;
        font-size: 14px;
        box-sizing: border-box;
        border: 1px solid rgb(245, 245, 245);
        transition: all 0.3s;
        &:placeholder-shown {
          font-size: 12px;
        }
        &:focus {
          border: 1px solid rgb(245, 108, 108) !important;
        }
        &:hover {
          border: 1px solid rgba(245, 108, 108, 0.5) !important;
        }
      }
      textarea {
        margin-top: 10px;
        width: 100%;
        resize: none;
        border-radius: 16px;
        outline: none;
        border: 1px solid rgb(245, 245, 245);
        height: 100px;
        padding: 10px;
        box-sizing: border-box;
        font-size: 15px;
        color: #6e6e6e;
        &:focus {
          border: 1px solid rgb(245, 108, 108) !important;
        }
        &:hover {
          border: 1px solid rgba(245, 108, 108, 0.5) !important;
        }
      }
    }
    .submit {
      height: 38px;
      background-color: #f93a08;
      border-radius: 16px;
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 12px;
      margin-top: 30px;
      cursor: pointer;
      padding: 2px 5px;
      &:hover {
        background-color: rgb(204, 44, 5);
      }
    }
  }
  .center {
    padding: 20px;
    margin-top: 20px;
    border-radius: 16px;
    img {
      width: 50px;
      height: 50px;
    }
    .pagination {
      margin-top: 20px;
    }
  }
}
</style>
